﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace C
{
    public partial class C : Form
    {
        public C()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BoxAdd("===================");
            BoxAdd("===================");

            try
            {
                int port = 5080;
                string host = "192.168.1.102";

                ///创建终结点EndPoint
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndpoint实例


                ///创建socket并连接到服务器
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
                BoxAdd("Conneting…");
                c.Connect(ipe);//连接到服务器


                ///向服务器发送信息
                string sendStr = "ZZZZXXXXXXZZZZZZZ";
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字符串编码为字节
                BoxAdd("Send Message");
                c.Send(bs, bs.Length, 0);//发送信息


                ///接受从服务器返回的信息
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                BoxAdd("client get message:"+recvStr);

                ///一定记着用完socket后要关闭
                c.Close();

            }
            catch (ArgumentNullException ex)
            {
                BoxAdd(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }




        private delegate int myDele(string s);
        private void BoxAdd(string s)
        {
            this.Invoke(new myDele(listBox1.Items.Add),s);
        }

    }
}

